﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Api.Sales.Orders.Formatters
{
    public class XmlFormatter : MediaTypeFormatter
    {
        public XmlFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
            SupportedEncodings.Add(Encoding.UTF8);
            SupportedEncodings.Add(Encoding.Unicode);
        }

        public override bool CanReadType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("Type");

            return true;
        }

        public override bool CanWriteType(Type type)
        {
            return true;
        }

        public override Task<object> ReadFromStreamAsync(
            Type type, 
            Stream readStream, 
            HttpContent content, 
            IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew(() =>
            {
                using (var streamReader = new StreamReader(readStream))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(readStream);
                    string jsonResponse = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None, true);
                    return JsonConvert.DeserializeObject(jsonResponse);
                }
            });
        }

        public override Task WriteToStreamAsync(
            Type type,
            object value,
            Stream writeStream,
            HttpContent content,
            TransportContext transportContext)
        {
            return Task.Factory.StartNew(() =>
            {
                var jsonString = JsonConvert.SerializeObject(value);
                var xmlDocument = JsonConvert.DeserializeXmlNode(jsonString, "xml", true);
                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Save(writeStream);
            });
        }
    }
}